package com.jinxin.platform.cdsmsmgr.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.exceptions.ClientException;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cdsmsmgr.alisms.AliSms;
import com.jinxin.platform.cdsmsmgr.alisms.SmsFactory;
import com.jinxin.platform.cdsmsmgr.mapper.CdsmsmgrFileMapper;
import com.jinxin.platform.cdsmsmgr.mapper.SmsAkInfoMapper;
import com.jinxin.platform.cdsmsmgr.mapper.SmsBusinessInfoMapper;
import com.jinxin.platform.cdsmsmgr.mapper.SmsSignInfoMapper;
import com.jinxin.platform.cdsmsmgr.pojo.domains.*;
import com.jinxin.platform.cdsmsmgr.pojo.entity.*;
import com.jinxin.platform.cdsmsmgr.pojo.enums.AuditStatusEnum;
import com.jinxin.platform.cdsmsmgr.pojo.enums.BusinessTypeEnum;
import com.jinxin.platform.cdsmsmgr.pojo.enums.SqlStatusEnum;
import com.jinxin.platform.cdsmsmgr.pojo.vo.SignInfo;
import com.jinxin.platform.cdsmsmgr.rpc.SysUserRpc;
import com.jinxin.platform.cdsmsmgr.service.ISmsSignService;
import com.jinxin.platform.cdsmsmgr.utils.DateUtil;
import com.jinxin.platform.cdsmsmgr.utils.IdWorker;
import com.jinxin.platform.cdsmsmgr.utils.TxSmsUtil;
import com.jinxin.platform.cdsmsmgr.utils.Utils;
import com.tencentcloudapi.sms.v20210111.models.DescribeSignListStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2020-06-29
 * @Author: Lingnan
 **/
@Service
public class SmsSignServiceImpl implements ISmsSignService {
    @Autowired
    private SmsSignInfoMapper signInfoMapper;
    @Autowired
    private SysUserRpc sysUserRpc;
    @Autowired
    private SmsAkInfoMapper akInfoMapper;
    @Autowired
    private CdsmsmgrFileMapper cdsmsmgrFileMapper;
    @Autowired
    private SmsBusinessInfoMapper businessInfoMapper;
    @Resource
    private IdWorker idWorker;

    @Override
    public List<SmsSignInfo> listPage(HashMap param) {
        return signInfoMapper.listPage(param);
    }

    @Override
    public int listPageCount(HashMap param) {
        return signInfoMapper.listPageCount(param);
    }

    @Override
    public ResultEntity saveOrUpdate(SmsSignInfo signInfo) {
        SysUserVO currentUser = sysUserRpc.getCurrentUser();
        if(currentUser == null) {
            return new ResultEntity(CommonCodeEntity.NO_LOGIN,"未登录用户","");
        }
        int count;
        if(!StringUtils.isEmpty(signInfo.getId())){
            count = signInfoMapper.updateByKey(signInfo);
        }else {
            signInfo.setId(Utils.getMillPrimaryKey());
            signInfo.setCreateTime(LocalDateTime.now());
            signInfo.setApplyUser(currentUser.getUserAccount());
            if(signInfo.getStatus() == null){
                signInfo.setStatus(Constant.SMS_STATUS_AUDITING);
            }
            count = signInfoMapper.insert(signInfo);
        }
        if(count > 0){
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc",signInfo);
        }else {
            return new ResultEntity(CommonCodeEntity.FAIL,"保存失败","");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultEntity deleteById(String id) {
        if(StringUtils.isEmpty(id)){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"id为空","");
        }
        SmsSignInfo smsSignInfo = signInfoMapper.selectByKey(id);
        if(smsSignInfo == null){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"签名不存在","");
        }
        Integer accountType = smsSignInfo.getAccountType();
        int count;
        if(Constant.ACCOUNT_TYPE_TX.equals(accountType)){//腾讯的逻辑删除
            SmsSignInfo signInfoNew = new SmsSignInfo();
            signInfoNew.setId(id);
            signInfoNew.setIsDel(Constant.IS_DEL_YES);
            count = signInfoMapper.updateByKey(signInfoNew);
        }else {
            count = signInfoMapper.deleteByKey(id);
        }
        if(count > 0){
            businessInfoMapper.setSignNull(id,accountType);
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc","");
        }
        return new ResultEntity(CommonCodeEntity.FAIL,"删除失败","");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultEntity addSmsSign(SmsSignInfo signInfo) {
        SysUserVO currentUser = sysUserRpc.getCurrentUser();
        if(currentUser == null) {
            return new ResultEntity(CommonCodeEntity.NO_LOGIN,"未登录用户","");
        }
        HashMap param = new HashMap();
        String userAccount = currentUser.getUserAccount();
        param.put("userAccount", Constant.ACCOUNT_ADMIN);//admin
        SmsAkInfo smsAkInfo = akInfoMapper.selectOne(param);
        String accountType = smsAkInfo.getThirdAccountType();
        if(smsAkInfo == null){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"请先配置accessKeyId和accessSecret","");
        }
        HashMap param2 = new HashMap();
        param2.put("signName",signInfo.getSignName());
        param2.put("scene",signInfo.getScene());
        param2.put("applyUser", Constant.ACCOUNT_ADMIN);
        param2.put("accountType", signInfo.getAccountType());
        SmsSignInfo smsSignInfo = signInfoMapper.selectOne(param2);
        if(smsSignInfo != null){
            if(Constant.TX_ACCOUNT.equals(accountType)) {//腾讯的可能是逻辑删除的
                SmsSignInfo signInfoNew = new SmsSignInfo();
                signInfoNew.setId(smsSignInfo.getId());
                signInfoNew.setIsDel(Constant.IS_DEL_NO);
                signInfoMapper.updateByKey(signInfoNew);
                return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc",smsSignInfo);
            }else {
                return new ResultEntity(CommonCodeEntity.ALREADY_EXIST,"相同适用场景的短信签名已存在","");
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put(SmsConstant.ACCESS_KEY_ID, smsAkInfo.getAkId());
        map.put(SmsConstant.ACCESS_SECERT, smsAkInfo.getAkSecret());
        map.put(SmsConstant.SIGN_NAME, signInfo.getSignName());
        try {
            Map<String, Object> signResultMap = SmsFactory.aliQuerySmsSign(map);
            if(signResultMap.containsKey(SmsConstant.RESULT)){
                SignResult signResult = (SignResult)signResultMap.get((SmsConstant.RESULT));
                if(signResult == null){
                    return new ResultEntity(CommonCodeEntity.FAIL,"申请的签名不存在","");
                }
                if(!Constant.STRING_OK.equals(signResult.getCode())){
                    return new ResultEntity(CommonCodeEntity.FAIL,signResult.getMessage(),"");
                }
                signInfo.setCreateTime(LocalDateTime.now());
                signInfo.setStatus(signResult.getSignStatus());
                signInfo.setReason(signResult.getReason());
            }
        } catch (ClientException e) {
            e.printStackTrace();
            return new ResultEntity(CommonCodeEntity.FAIL,"调用阿里短信服务失败","");
        }
        signInfo.setId(Utils.getMillPrimaryKey());
        signInfo.setApplyUser(userAccount);
        signInfo.setIsDel(Constant.IS_DEL_NO);
        int count = signInfoMapper.insert(signInfo);
        if(count > 0){
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc",signInfo);
        }else {
            return new ResultEntity(CommonCodeEntity.FAIL,"保存失败","");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult applyAliSmsSign(AliSmsSignInfo smsSignInfo) {
        String id = smsSignInfo.getId();
        boolean isApply = StringUtils.isEmpty(id);
        JsonResult jsonResult = queryAkInfo();
        if(!jsonResult.getSuccess()){
            return jsonResult;
        }
        SmsAkInfo smsAkInfo = (SmsAkInfo) jsonResult.getData();
        Map<String, Object> map = new HashMap<>();
        map.put(SmsConstant.ACCESS_KEY_ID, smsAkInfo.getAkId());
        map.put(SmsConstant.ACCESS_SECERT, smsAkInfo.getAkSecret());
        String signName = smsSignInfo.getSignName();
        map.put(SmsConstant.SIGN_NAME, signName);
        Integer source = smsSignInfo.getSource();
        map.put(SmsConstant.SIGN_SOURCE, source);
        map.put(SmsConstant.SIGN_TYPE, smsSignInfo.getScene());
        String explain = smsSignInfo.getExplain();
        map.put(SmsConstant.SIGN_REMARK, explain);
        List<SignFile> signFileList = new ArrayList<>();
        FileInfo[] fileList = smsSignInfo.getFileList();
        for(FileInfo fileInfo : fileList){
            SignFile signFile = new SignFile();
            String name = fileInfo.getName();
            String fileSuffix = name.substring(name.lastIndexOf(".") + 1);
            signFile.setFileSuffix(fileSuffix.toUpperCase());
            signFile.setFileContents(fileInfo.getContent().replaceFirst(Constant.IMG_BASE64_PREFIX,""));
            signFileList.add(signFile);
        }
        map.put(SmsConstant.SIGN_FILE, signFileList);
        try {
            AddAliSignResult addAliSignResult = SmsFactory.addSmsSign(map,isApply);
            if(addAliSignResult != null && Constant.STRING_OK.equals(addAliSignResult.getCode())){
                SmsSignInfo signInfo = new SmsSignInfo();
                String signId;
                if(isApply){
                    signId = Utils.getMillPrimaryKey();
                }else {
                    signId = id;
                }
                signInfo.setId(signId);
                signInfo.setSignName(signName);
                signInfo.setScene(Constant.SMS_SCENE_COMMON);
                signInfo.setSource(source);
                signInfo.setExplain(explain);
                signInfo.setStatus(Constant.SMS_STATUS_AUDITING);
                signInfo.setCreateTime(LocalDateTime.now());
                signInfo.setApplyUser(jsonResult.getMsg());
                signInfo.setAccountType(Constant.ACCOUNT_TYPE_ALI);
                signInfo.setIsDel(Constant.IS_DEL_NO);
                String msg;
                if(isApply){
                    signInfoMapper.insert(signInfo);
                    msg = "申请签名成功";
                }else {
                    signInfoMapper.updateByKey(signInfo);
                    msg = "修改申请签名成功";
                }
                if(!isApply){
                    cdsmsmgrFileMapper.deleteBySignId(signId);
                }
                for(FileInfo fileInfo : fileList){
                    CdsmsmgrFile file = new CdsmsmgrFile();
                    String name = fileInfo.getName();
                    file.setId(idWorker.nextId()+"");
                    file.setName(name);
                    file.setContent(fileInfo.getContent());
                    file.setSignId(signId);
                    cdsmsmgrFileMapper.insert(file);
                }
                return JsonResult.ok(msg,null);
            }else {
                return JsonResult.error(addAliSignResult.getMessage());
            }
        } catch (ClientException e) {
            e.printStackTrace();
            return JsonResult.error("申请签名异常: " + e.getMessage());
        }
    }

    @Override
    public JsonResult queryById(String id) {
        SmsSignInfo smsSignInfo = signInfoMapper.selectByKey(id);
        if(smsSignInfo == null){
            return JsonResult.error("无对应签名");
        }
        HashMap param = new HashMap();
        param.put("signId",id);
        List<CdsmsmgrFile> list = cdsmsmgrFileMapper.list(param);
        return JsonResult.ok("success",list);
    }

    private JsonResult queryAkInfo(){
        SysUserVO currentUser = sysUserRpc.getCurrentUser();
        if(currentUser == null) {
            return JsonResult.error("未登录");
        }
        HashMap param = new HashMap();
        param.put("userAccount", Constant.ACCOUNT_ADMIN);//admin
        SmsAkInfo smsAkInfo = akInfoMapper.selectOne(param);
        if(smsAkInfo == null){
            return JsonResult.error("请先配置accessKeyId和accessSecret");
        }
        return JsonResult.ok(currentUser.getUserAccount(),smsAkInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult applyTxSmsSign(TxSmsSignInfo smsSignInfo) {
        JsonResult jsonResult = queryAkInfo();
        if(!jsonResult.getSuccess()){
            return jsonResult;
        }
        SmsAkInfo smsAkInfo = (SmsAkInfo) jsonResult.getData();
        String signId = smsSignInfo.getSignId();
        String id = smsSignInfo.getId();
        boolean isApply = StringUtils.isEmpty(signId);
        JsonResult jsonResult2;
        String signName = smsSignInfo.getSignName();
        Integer signType = smsSignInfo.getSource();
        String proofImage = smsSignInfo.getProofImage();
        String remark = smsSignInfo.getExplain();
        Integer docType = smsSignInfo.getDocType();
        if(isApply){
            TxAddSmsSignParam smsSignParam = new TxAddSmsSignParam();
            smsSignParam.setSecretId(smsAkInfo.getAkId());
            smsSignParam.setSecretKey(smsAkInfo.getAkSecret());
            smsSignParam.setSignName(signName);
            smsSignParam.setSignType(signType);
            smsSignParam.setDocumentType(docType);
            smsSignParam.setInternational(Constant.SMS_TYPE_DOMESTIC);
            smsSignParam.setSignPurpose(Constant.SMS_SIGNPURPOSE_SELF);
            smsSignParam.setProofImage(proofImage.replaceFirst(Constant.IMG_BASE64_PREFIX,""));
            smsSignParam.setRemark(remark);
            jsonResult2 = TxSmsUtil.addSmsSign(smsSignParam);
        }else {
            TxModifySmsSignParam smsSignParam = new TxModifySmsSignParam();
            smsSignParam.setSecretId(smsAkInfo.getAkId());
            smsSignParam.setSecretKey(smsAkInfo.getAkSecret());
            smsSignParam.setSignId(Integer.valueOf(signId));
            smsSignParam.setSignName(signName);
            smsSignParam.setSignType(signType);
            smsSignParam.setDocumentType(docType);
            smsSignParam.setInternational(Constant.SMS_TYPE_DOMESTIC);
            smsSignParam.setSignPurpose(Constant.SMS_SIGNPURPOSE_SELF);
            smsSignParam.setProofImage(proofImage.replaceFirst(Constant.IMG_BASE64_PREFIX,""));
            smsSignParam.setRemark(remark);
            jsonResult2 = TxSmsUtil.modifySmsSign(smsSignParam);
        }
        if(jsonResult2.getSuccess()){
            SmsSignInfo signInfo = new SmsSignInfo();
            if(isApply){
                signInfo.setId(Utils.getMillPrimaryKey());
            }else {
                signInfo.setId(id);
            }
            signInfo.setSignName(signName);
            signInfo.setDomainName(smsSignInfo.getProofName());//图片名称
            signInfo.setScene(Constant.SMS_SCENE_COMMON);
            signInfo.setSource(signType);
            signInfo.setExplain(remark);
            signInfo.setStatus(Constant.SMS_STATUS_AUDITING);
            signInfo.setCreateTime(LocalDateTime.now());
            signInfo.setApplyUser(jsonResult.getMsg());
            signInfo.setAccountType(Constant.ACCOUNT_TYPE_TX);
            signInfo.setIsDel(Constant.IS_DEL_NO);
            signInfo.setSignId((Long) jsonResult2.getData());
            signInfo.setDocType(docType);
            signInfo.setBusinessLicense(proofImage);
            String msg;
            if(isApply){
                signInfoMapper.insert(signInfo);
                msg = "申请成功";
            }else {
                signInfoMapper.updateByKey(signInfo);
                msg = "修改申请成功";
            }
            return JsonResult.ok(msg,null);
        }
        return jsonResult2;
    }

    @Override
    public ResultEntity updateStatus() {
        SysUserVO currentUser = sysUserRpc.getCurrentUser();
        if(currentUser == null) {
            return new ResultEntity(CommonCodeEntity.NO_LOGIN,"未登录用户","");
        }
        HashMap param = new HashMap();
        String userAccount = currentUser.getUserAccount();
        param.put("userAccount", Constant.ACCOUNT_ADMIN);
        SmsAkInfo smsAkInfo = akInfoMapper.selectOne(param);
        if(smsAkInfo == null){
            return new ResultEntity(CommonCodeEntity.FAIL,"accessKeyId和accessSecret未配置","");
        }
        HashMap param2 = new HashMap();
        param2.put("applyUser", currentUser.getUserAccount());
        List<SmsSignInfo> list = signInfoMapper.list(param2);
        AliSms aliSms = new AliSms(smsAkInfo.getAkId(), smsAkInfo.getAkSecret());
        for (SmsSignInfo smsSignInfo : list){
            try {
                CommonResponse response = aliSms.querySmsSign(smsSignInfo.getSignName());
                SignResult signResult = JSONObject.parseObject(response.getData(), SignResult.class);
                if(signResult != null){
                    Integer status = signResult.getSignStatus();
                    Integer oldStatus = smsSignInfo.getStatus();
                    // 数据库签名是审核中与阿里平台的对比
                    if(status != null && !status.equals(oldStatus) && Constant.SMS_STATUS_AUDITING.equals(oldStatus)){
                        smsSignInfo.setStatus(status);
                        smsSignInfo.setReason(signResult.getReason());
                        signInfoMapper.updateByKey(smsSignInfo);
                        // 不在审核中，阿里平台查询结果不存在，需删除数据库中的记录
                    }else if(Constant.SMS_SIGN_RESULT_ERROR_CODE_ILLEGAL.equals(signResult.getCode()) && !Constant.SMS_STATUS_AUDITING.equals(oldStatus)){ // 在阿里平台已经删除的在数据库也需要删除
                        signInfoMapper.deleteByKey(smsSignInfo.getId());
                    }

                }
            } catch (ClientException e) {
                e.printStackTrace();
                return new ResultEntity(CommonCodeEntity.FAIL,"查询短信签名失败","");
            }
        }
        return new ResultEntity(CommonCodeEntity.FAIL,"更新状态成功","");
    }

    @Override
    public SmsSignInfo getById(String id) {
        return signInfoMapper.selectByKey(id);
    }

    @Override
    public JsonResult querySmsSignList() {
        SysUserVO currentUser = sysUserRpc.getCurrentUser();
        if(currentUser == null) {
            return JsonResult.error("未登录");
        }
        HashMap param = new HashMap();
        param.put("userAccount", Constant.ACCOUNT_ADMIN);
        SmsAkInfo smsAkInfo = akInfoMapper.selectOne(param);
        if(smsAkInfo == null){
            return JsonResult.error("秘钥对未配置");
        }
        String thirdAccountType = smsAkInfo.getThirdAccountType();
        String akId = smsAkInfo.getAkId();
        String akSecret = smsAkInfo.getAkSecret();
        List<SignInfo> signInfoList = new ArrayList<>();
        if(Constant.TX_ACCOUNT.equals(thirdAccountType)){
            param.put("accountType",Constant.ACCOUNT_TYPE_TX);
            param.put("idDel",Constant.IS_DEL_YES);//已删除的
            List<SmsSignInfo> list = signInfoMapper.list(param);
            for(SmsSignInfo smsSignInfo : list){
                SignInfo signInfo = new SignInfo();
                signInfo.setId(smsSignInfo.getId());
                signInfo.setSignId(smsSignInfo.getSignId());
                signInfo.setSignName(smsSignInfo.getSignName());
                signInfo.setApplyTime(DateUtil.getDateTimeAsString(smsSignInfo.getCreateTime(),null));
                signInfo.setStatus(SqlStatusEnum.getDesc(smsSignInfo.getStatus()));
                signInfo.setReason(smsSignInfo.getReason());
                signInfoList.add(signInfo);
            }
        }else {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put(SmsConstant.ACCESS_KEY_ID,akId);
            paramMap.put(SmsConstant.ACCESS_SECERT,akSecret);
            int pageSize = SmsConstant.PAGE_SIZE;
            paramMap.put(SmsConstant.QUERY_PAGE_SIZE,pageSize);
            try {
                AliSign aliSign = SmsFactory.aliQuerySmsSignList(paramMap);
                if(aliSign != null && aliSign.getTotalCount() > 0){
                    List<SignInfo> signList = new ArrayList<>();
                    setSignList(signList, aliSign);
                    int totalCount = aliSign.getTotalCount().intValue();
                    int page = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
                    for (int i = 2; i < page; i++) {
                        paramMap.put(SmsConstant.QUERY_PAGE_INDEX,i);
                        paramMap.put(SmsConstant.QUERY_PAGE_SIZE,pageSize);
                        AliSign aliSign2 = SmsFactory.aliQuerySmsSignList(paramMap);
                        if(aliSign2 != null && aliSign2.getSmsSignList().size() > 0){
                            setSignList(signList, aliSign2);
                        }
                    }
                    // 去除本地库已有的数据
                    param.put("accountType",Constant.ACCOUNT_TYPE_ALI);
                    param.put("idDel",Constant.IS_DEL_NO);//未删除的
                    List<SmsSignInfo> list = signInfoMapper.list(param);
                    Set<String> codeSet = list.stream().map(SmsSignInfo::getSignName).collect(Collectors.toSet());
                    for(SignInfo templateVo : signList){
                        if(!codeSet.contains(templateVo.getSignName())){
                            signInfoList.add(templateVo);
                        }
                    }
                }
            } catch (ClientException e) {
                e.printStackTrace();
                return JsonResult.error("查询短信签名列表失败");
            }
        }
        return JsonResult.ok("success",signInfoList);
    }

    private void setSignList(List<SignInfo> signInfoList, AliSign aliSign) {
        List<AliSignObj> smsSignList = aliSign.getSmsSignList();
        for(AliSignObj signObj : smsSignList){
            String auditStatus = signObj.getAuditStatus();
            SignInfo signInfo = new SignInfo();
            signInfo.setScene(BusinessTypeEnum.getCode(signObj.getBusinessType()));
            signInfo.setSignName(signObj.getSignName());
            signInfo.setApplyTime(signObj.getCreateDate());
            String statusDesc = AuditStatusEnum.getDesc(auditStatus);
            signInfo.setStatus(statusDesc);
            if(Constant.AUDIT_STATE_NOT_PASS.equals(auditStatus)){
                AliAuditReason reason = signObj.getReason();
                signInfo.setReason(statusDesc+","+reason.getRejectInfo());
            }
            signInfoList.add(signInfo);
        }
    }

    @Override
    public JsonResult syncSmsSign(List<SignInfo> signInfoList) {
        SysUserVO currentUser = sysUserRpc.getCurrentUser();
        if(currentUser == null) {
            return JsonResult.error("未登录");
        }
        int count = 0;
        for(SignInfo signInfo : signInfoList){
            String id = signInfo.getId();
            SmsSignInfo smsSignInfo = new SmsSignInfo();
            if(StringUtils.isEmpty(id)){//id为空说明是第三方未入库的签名
                smsSignInfo.setId(Utils.getMillPrimaryKey());
                smsSignInfo.setSignName(signInfo.getSignName());
                smsSignInfo.setScene(signInfo.getScene());
                smsSignInfo.setStatus(SqlStatusEnum.getCode(signInfo.getStatus()));
                smsSignInfo.setCreateTime(DateUtil.timeString2LocalDateTime(signInfo.getApplyTime(),null));
                smsSignInfo.setApplyUser(currentUser.getUserAccount());
                smsSignInfo.setReason(signInfo.getReason());
                smsSignInfo.setAccountType(signInfo.getType());
                smsSignInfo.setIsDel(Constant.IS_DEL_NO);
                smsSignInfo.setSignId(signInfo.getSignId());
                count += signInfoMapper.insert(smsSignInfo);
            }else { // 不为空说明是逻辑删除的签名,更新删除状态即可
                smsSignInfo.setId(id);
                smsSignInfo.setIsDel(Constant.IS_DEL_NO);
                count += signInfoMapper.updateByKey(smsSignInfo);
            }
        }
        return JsonResult.ok("成功同步"+count+"条签名",null);
    }

    @Override
    public JsonResult freshStatus(String id) {
        SmsSignInfo smsSignInfo = signInfoMapper.selectByKey(id);
        if(smsSignInfo == null){
            return JsonResult.error("签名不存在");
        }
        HashMap param = new HashMap();
        param.put("userAccount", Constant.ACCOUNT_ADMIN);
        SmsAkInfo smsAkInfo = akInfoMapper.selectOne(param);
        if(smsAkInfo == null){
            return JsonResult.error("秘钥对未配置");
        }
        String akId = smsAkInfo.getAkId();
        String akSecret = smsAkInfo.getAkSecret();
        Integer accountType = smsSignInfo.getAccountType();
        Integer oldStatus = smsSignInfo.getStatus();
        if(Constant.ACCOUNT_TYPE_ALI.equals(accountType)){
            AliSms aliSms = new AliSms(akId, akSecret);
            try {
                CommonResponse response = aliSms.querySmsSign(smsSignInfo.getSignName());
                SignResult signResult = JSONObject.parseObject(response.getData(), SignResult.class);
                if(signResult != null){
                    Integer status = signResult.getSignStatus();
                    // 数据库签名是审核中与阿里平台的对比
                    if(status != null && !status.equals(oldStatus) && Constant.SMS_STATUS_AUDITING.equals(oldStatus)){
                        SmsSignInfo smsSignInfoNew = new SmsSignInfo();
                        smsSignInfoNew.setId(id);
                        smsSignInfoNew.setStatus(status);
                        smsSignInfoNew.setReason(signResult.getReason());
                        signInfoMapper.updateByKey(smsSignInfoNew);
                        // 不在审核中，阿里平台查询结果不存在，需删除数据库中的记录
                    }else if(Constant.SMS_SIGN_RESULT_ERROR_CODE_ILLEGAL.equals(signResult.getCode()) &&
                            !Constant.SMS_STATUS_AUDITING.equals(oldStatus)){ // 在阿里平台已经删除的在数据库也需要删除
                        signInfoMapper.deleteByKey(smsSignInfo.getId());
                    }
                    return JsonResult.ok("刷新审核状态成功",null);
                }
            } catch (ClientException e) {
                e.printStackTrace();
                return JsonResult.error("查询短信签名失败");
            }
        }else {
            TxSmsSignQueryParam smsSignQueryParam = new TxSmsSignQueryParam();
            smsSignQueryParam.setSecretId(akId);
            smsSignQueryParam.setSecretKey(akSecret);
            Long[] signIdSet = new Long[]{smsSignInfo.getSignId()};
            smsSignQueryParam.setSignIdSet(signIdSet);
            smsSignQueryParam.setInternational(Constant.SMS_TYPE_DOMESTIC);
            JsonResult jsonResult = TxSmsUtil.describeSmsSignList(smsSignQueryParam);
            if(jsonResult.getSuccess()){
                DescribeSignListStatus [] signListStatuses = (DescribeSignListStatus[]) jsonResult.getData();
                if(signListStatuses.length > 0){
                    DescribeSignListStatus signStatus = signListStatuses[0];
                    // 申请签名状态，其中0表示审核通过，1表示审核中。-1：表示审核未通过或审核失败。
                    Long statusCode = signStatus.getStatusCode();
                    int status = 0;
                    if(statusCode == Constant.AUDIT_STATUS_INIT){
                        status = Constant.SMS_STATUS_AUDITING;//0
                    }else if(statusCode == Constant.AUDIT_STATUS_PASS){
                        status = Constant.SMS_STATUS_AUDIED_PASS;//1
                    }else if(statusCode == Constant.AUDIT_STATUS_NOT_PASS){
                        status = Constant.SMS_STATUS_AUDIED_UNPASS;//2
                    }
                    if(status != oldStatus && Constant.SMS_STATUS_AUDITING.equals(oldStatus)){
                        SmsSignInfo smsSignInfoNew = new SmsSignInfo();
                        smsSignInfoNew.setId(id);
                        smsSignInfoNew.setStatus(status);
                        smsSignInfoNew.setReason(signStatus.getReviewReply());
                        signInfoMapper.updateByKey(smsSignInfoNew);
                    }
                }
            }
            return jsonResult;
        }
        return null;
    }
}
